<?php
/**
 * Created by PhpStorm.
 * User: wo
 * Date: 2019/8/27
 * Time: 19:48
 */
class ShareApp extends MallbaseApp{
    //分享注册新用户
    function index(){
        $type = '';
        if($_GET['type']){
            $type = $_GET['type'];
        }
        $this->assign('type',$type);
        $wish_id = '';
        if($_GET['wish_id']){
            $wish_id = $_GET['wish_id'];
        }
        $this->assign('wish_id',$wish_id);
        $token = '';
        if($_GET['token']){
            $token = $_GET['token'];
        }
        if($_GET['goods_id']){
            $goods_id = $this->get_decrypt($_GET['goods_id']);
            $this->assign('goods_id',$_GET['goods_id']);
        }
        $param['web_site'] = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
        $message = '分享注册：注册完整url'.json_encode($param);
        $writeMe = &m("member")->writeLog($message);


        $this->assign('token',$token);
//        $this->display('share.index.html');
        $this->display('share.404.html');
    }

    /**
     * @api {get}  注册相关接口
     */
    function shareRegister() {
        header("Content-type: text/html; charset=utf-8");
        $user_info = array();
        $phone_mob = $_POST['phone'];
        $msg_sign = $_POST['msg_sign'];
        $password = $_POST['password'];
        $confirm_password = $_POST['confirm_password'];
        $msg_code = $_POST['code'];
        $city = $_POST['city'];
        $token = $_POST['token']; //推荐人id
        $referid = array('user_id'=>0);
        if($token){
            $apptoken = &m('app_token');
            $referid = $apptoken->get(array('conditions'=>"token = '$token'"));
            if(empty($referid)){
                $referid = array('user_id'=>0);
            }
        }
        try{
           $param = array(
               'phone_mob' => $phone_mob,
               'msg_sign'  => $msg_sign,
               'password'  => $password,
               'confirm_password' => $confirm_password,
               'msg_code'  => $msg_code,
               'city'      => $city,
               'referid'   => $referid,
               'refer_type'=>1
           );
           $arr = $this->method($param);
        }catch(\Exception $e){
            $arr['code'] = -1;
            $arr['msg'] = '网络错误';
        }
        echo json_encode($arr);
        exit();
    }
    function method($param){
        $phone_mob = $param['phone_mob'];
        $msg_code = $param['msg_code'];
        $confirm_password = $param['confirm_password'];
        $password = $param['password'];
        $msg_sign = $param['msg_sign'];
        $city = $param['city'];
        $referid['user_id'] = $param['referid'];

        $param['web_site'] = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
        $message = '接收到的参数'.json_encode($param);
        $writeMe = &m("member")->writeLog($message);


        $arr['code'] = -1;
        $arr['msg'] = '缺少参数';
        if($phone_mob  && $msg_code  && $confirm_password && $password){
           $arr['msg'] = '短信验证码错误';
           if (md5('HomeIndexSet_password' . $msg_code) == $msg_sign) {
                $arr['msg'] = '注册失败，用户名长度为3-25之间！';
                $user_name = $phone_mob;
                $user_name_len = strlen($user_name);
                if ($user_name_len >= 3 && $user_name_len <= 25) {
                    $arr['msg'] = '输入两次密码不一致';
                    if ($password == $confirm_password) {
                        $arr['msg'] = '密码长度必须大于6位';
                        $passlen = strlen($password);
                        if ($passlen >= 6 && $passlen <= 20) {
                            //实例化
                            $region = &m('region');
                            $member = &m("member");
                            //验证手机号是否已存在
                            $memberInfo = $member->check_mobile($phone_mob);
                            $arr['code'] = -2; //用户已存在
                            $arr['msg'] = $memberInfo['msg'];
                            if($memberInfo['code'] == 1){

                                $store = &m("store");
                                $integrallog = &m('integral_log');
                                $appToken = &m('app_token');

                                //如果不传入token  根据地区选择注册人的店铺信息 反之选择分享人的店铺信息
                                if($referid['user_id'] == 0){
                                    //城市
                                    $res_city = $region->get(array('conditions' => 'region_name like "%'.$city.'%"'));
                                    $res_store = $store->get(array('conditions'=>'is_main = 0 AND region_id = '.$res_city['region_id']));
                                    if(!$res_store) {
                                        $res_store = $store->get(array('conditions' => 'is_main = 0 AND region_id = ' . $res_city['parent_id']));
                                    }

                                    if(!$res_store) {
                                        $res_store = $store->get(array('conditions' => 'is_main = 1'));
                                        if(!$res_store){
                                            echo json_encode(array('code'=>-1,'msg'=>'查找仓库失败'));
                                            exit();
                                        }
                                    }
                                }else {


                                    $parentInfo = $member->get(array('conditions' => 'user_id = ' . $referid['user_id']));
                                    $storeInfo = $store->get(array('conditions' => 'store_id = ' . $referid['user_id']));
                                    if (!empty($storeInfo)) {
                                        $res_store['store_id'] = $storeInfo['store_id'];
                                        $res_store['store_name'] = $storeInfo['store_name'];
                                    } else {
                                        $res_store['store_id'] = $parentInfo['s_id'];
                                        $res_store['store_name'] = $parentInfo['s_name'];
                                    }

                                    if ($parentInfo['first_class'] != 0) {
                                        //分享者是一级店铺
                                        $first_class = $parentInfo['first_class'];
                                            //分享者是二级店铺
                                        if ($parentInfo['second_class'] != 0) {
                                            $second_class = $parentInfo['second_class'];
                                                //分享者是二级店铺员工
                                            if ($parentInfo['third_class'] != 0) {
                                                $third_class = $parentInfo['third_class'];
                                                $fourth_class = $parentInfo['third_class'];
                                            } else {
                                                $fourth_class = $parentInfo['second_class'];
                                            }
                                        } else {
                                            $fourth_class = $parentInfo['first_class'];
                                            //分享者是一级店铺下员工
                                            if($parentInfo['third_class'] != 0){
                                                $fourth_class = $parentInfo['third_class'];
                                                $third_class = $parentInfo['third_class'];
                                            }
                                        }
                                    } else {
                                        //普通分享
                                        $fourth_class = $referid['user_id'];
                                    }
                                }

                                if($res_store){
                                    $user_id = $member->share_register($user_name, $password, '', array(
                                            'phone_mob' => $phone_mob,
                                            's_id'=>$res_store['store_id'],
                                            's_name'=>$res_store['store_name'],
                                            'referid'=>$referid['user_id'],
                                            'refer_type'=>$param['refer_type'],
                                            'first_class' => $first_class?$first_class:0,
                                            'second_class' => $second_class?$second_class:0,
                                            'third_class' => $third_class?$third_class:0,
                                            'fourth_class' => $fourth_class?$fourth_class:0
                                        )
                                    );
                                    $arr['msg'] = $user_id['msg'];
                                    if($user_id['code'] == 1){
                                        $token = md5('user_'.$user_id['result'].'_'.'_'.time());
                                        //保存到app_token表
                                        $appToken->add(array(
                                            'user_id' => $user_id['result'],
                                            'token' => $token
                                        ));
                                        $arr['code'] = 1;
                                        $arr['msg'] = '注册成功';
                                        $arr['user_id'] = $user_id['result'];
                                        $arr['token'] = $token;
                                    }else{
                                        $arr['code'] = -1;
                                        $arr['msg'] = '注册失败';
                                    }
                                }
                            }
                        }
                    }
                }
           }
        }

        $message = '得到结果参数回馈：'.json_encode($arr);
        $writeMe = &m("member")->writelog($message);
        return $arr;
    }

    /**
     * @api {get} 发送短信接口
     */
    function send_messages() {
        $to_mobile = $_POST['mobile'];
        if (!$to_mobile) {
            echo json_encode(array(
                'code' => -1,
                'message' => '手机号码为空',
            ));
            exit;
        }
        $member = &m('member');
        $memberInfo = $member->check_mobile($to_mobile);
        if($memberInfo['code'] == -1){
            echo json_encode(array(
                'code' => $memberInfo['code'],
                'message' => $memberInfo['msg'],
            ));
            exit;
        }
        $msgLog = &m('msglog');
        $result = $msgLog->send_msg_system('register', $to_mobile);
        $msg_sign = md5('HomeIndexSet_password' . $_SESSION['MobileConfirmCode']);
        echo json_encode(array(
            'code' => $result['code'],
            'message' => $result['msg'],
            'result' => array('msg_sign' => $msg_sign)
        ));
        exit;
    }


    /** 心愿单分享用户*/
    function shareWish(){
        $wish_id = $_GET['wish_id'];
        // $token = $_GET['token'];
        $code = $_GET['invite_code'];
        if(!$wish_id || !$code){
            $this->display('share.404.html');
            exit();
        }
        $model = &m('wish');
        $goodsspec = &m('goodsspec');
        $wishPayLog = &m('wish_pay_log');
        $wishLog = &m('wish_log');
        $goods = &m('goods');


        //查看心愿单内容
        $wishInfo = $model->get(array(
            'conditions' => 'id = '.$wish_id
        ));
        if(!empty($wishInfo)){
            //查看当前规格信息
            $goodsspecInfo = $goodsspec->get(array('conditions'=>'spec_id = '.$wishInfo['spec_id']));
            $goodsInfo = $goods->get(array('conditions'=>"goods_id = ".$goodsspecInfo['goods_id']));
            $conditions = 'wish_id = '.$wish_id;

            //查到所有砍价记录
            $log = $wishLog->find(array(
                'fields'  => 'wish_log.*,member.user_name',
                'join'    =>  'has_member',
                'conditions'    =>$conditions,
                'count' => true,
            ));
            $member = &m('member');
            foreach($log as $k=>$v){
                $memberInfo = $member->get(array(
                    'conditions' => 'user_id ='.$v['inviter_id'],
                    'fields'     => 'user_name',
                ));
                $log[$k]['people_name'] = $memberInfo['user_name'];
                if(preg_match("/^1[345678]{1}\d{9}$/",$memberInfo['user_name'])){
                    $log[$k]['people_name'] = substr_replace($memberInfo['user_name'], '****', 3, 4);
                }
            }
            //首款金额
            $first_paragraph = $wishPayLog->getPayLog($wish_id,1);
            //总砍价金额
            $chop_paragraph = $wishLog->getInvalid($wish_id);
            //总金额（已获得帮助加上已付金额）
            $total_price = $first_paragraph + $chop_paragraph;
            //剩余金额
            $surplus_price = $wishInfo['goods_price'] - $total_price;
            //帮砍比例
            $te_protion = 100 - round($total_price/$wishInfo['goods_price']*100);
            $te_cha = round($total_price/$wishInfo['goods_price']*100);
            $portion = $te_protion.'%';
            $cha = $te_cha.'%';
            if($te_protion <= 0){
                $portion = '0%';
                $cha = '100%';
            }
            $discount = $wishInfo['discount'] * 10;
//            if($discount >= 10){
//                $discount = 1;
//            }
            $info = array(
                'list' => $log,
                'surplus_price' => $surplus_price,      //剩余金额
                'goodsSpecInfo' => $goodsspecInfo,
                'goodsInfo'     => $goodsInfo,
                'info'          => $wishInfo,
                'protion'       => $portion,
                'code'          => $code,
                'cha'           => $cha,
                'chop_paragraph'=> $chop_paragraph,         //总帮砍金额
                'listCount'     => count($log),
                'total_price'   => $total_price,
                'discount'      => $discount,
                'firstPayment'  => $wishPayLog->get(
                    array("conditions"=>"wish_id = ".$wish_id,' AND type = 1',
                            'join' =>"has_member",
                            'fields'=>"member.phone_mob,wish_pay_log.*"
                        )),
            );
            $info['firstPaymentPhone'] = substr_replace($info['firstPayment']['phone_mob'], '****', 3, 4);

            $this->assign('info',$info);
        }else{
            $this->display('share.404.html');
            exit();
        }
        $end_time = date('Y/m/d H:i:s',$wishInfo['add_time'] + 86400);
        $this->assign('end_time',$end_time);
        $this->assign('price',WISH_PRICE);
        $this->assign('wish_id',$wish_id);
        // $this->assign('token',$token);
        if($wishInfo['state'] == 0){
//            $this->display('share.wish_cancel.html');
            $this->display('share.404.html');
        }elseif($wishInfo['state'] == 2){
            $this->display('share.404.html');
//            $this->display('share.wish_success.html');
        }
        $this->display('share.404.html');
//        $this->display('share.wish.html');
    }

    /**心愿单砍单注册页面**/
    function registerHack(){
        $wish_id = $_GET['wish_id'];
        $invite_code = $_GET['invite_code'];
        if(!$wish_id || !$invite_code){
            $this->display('share.404.html');
            exit();
        }
        $param['web_site'] = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
        $message = '分享注册：注册完整url'.json_encode($param);
        $writeMe = &m("member")->writeLog($message);
        $this->assign('invite_code',$invite_code);
        $this->assign('wish_id',$wish_id);
        $this->display('share.404.html');
//        $this->display('share.registerHack.html');
    }
    /** 通过分享心愿单注册 */
    function shareWishRegister(){
        header("Content-type: text/html; charset=utf-8");
        $phone_mob = $_POST['phone'];
        $msg_sign = $_POST['msg_sign'];
        $password = $_POST['password'];
        $confirm_password = $_POST['confirm_password'];
        $msg_code = $_POST['code'];
        $city = $_POST['city'];
        $wish_id = $_POST['wish_id'];
        if(!$phone_mob || !$msg_sign || !$password || !$confirm_password || !$msg_code  || !$wish_id){
            echo json_encode(array('code'=> -1,'msg'=>'参数错误'));
            exit();
        }
        $code = -1;
        $msg = '';
        try{
            //查询当前心愿单状况
            $wish = &m('wish');
            $wishPaylog = &m("wish_pay_log");
            $wishLogModel = &m('wish_log');
            //查看心愿单内容
            $wishInfo = $wish->get(array('conditions'=>array('id'=>$wish_id)));
            $msg = '心愿单信息错误';
            if (!empty($wishInfo)) {
                $param = array(
                    'phone_mob' => $phone_mob,
                    'msg_sign'  => $msg_sign,
                    'password'  => $password,
                    'confirm_password' => $confirm_password,
                    'msg_code'  => $msg_code,
                    'city'      => $city,
                    'referid'   => $wishInfo['user_id'],
                    'refer_type'=> 2
                );
                $result = $this->method($param);
                //注册成功后进行砍单
                $msg = $result['msg'];
                if($result['code'] == 1){
//                $arr['msg'] = '心愿单状态不符合当前操作';
//                if($wishInfo['state'] == 1){
                    //以前的逻辑  作废
//                    //查询当前已支付金额 以及帮砍金额
//                    $wishpaylogMoney = $wishPaylog->getPayLog($wish_id,1);
//                    $wishlogMoney = $wishlog->getInvalid($wish_id);
//                    //期望价格 和 已付金额+帮砍金额 比较
//                    $goodsSpecInfo = &m("goodsspec")->get(array('conditions'=>'spec_id = '.$wishInfo['spec_id']));
//                    $total_price = $wishpaylogMoney + $wishlogMoney;
//                    if($wishInfo['goods_price'] > $total_price){
//                        $insertData = array(
//                            'user_id' => $referid['user_id'],//发起人
//                            'inviter_id' => $result['user_id'],//帮砍人id
//                            'wish_id' => $wish_id,          //心愿单id
//                            'money'   => WISH_LOG_PRICE,                //固定金额
//                            'msg'     => '帮砍金额',
//                            'create_time'=>time()
//                        );
//                        $insert = $wishlog->add($insertData);
//                        //再次查询当前金额和期望金额比较
//                        $newWishlogMoney = $wishlog->getInvalid($wish_id);
//                        $newTotalMoney = $wishpaylogMoney + $newWishlogMoney;
//
//                        if($wishInfo['goods_price'] <= $newTotalMoney){
//                            //调取生成订单接口
//                            $info = $wish->createOrder($wish_id);
//                            $arr['msg'] = $info['msg'];
//                            if($info['code'] == 1){
//                                $arr['code'] = 1;
//                                $arr['result'] = 'wish';
//                                $arr['data'] = array(
//                                    'wish_id' => $wish_id,
//                                    'token'   => $token,
//                                );
//                            }
//                        }else{
//                            if($insert){
//                                $arr['code'] = 1;
//                                $arr['msg'] = 'success';
//                                $arr['result'] = 'wish';
//                                $arr['data'] = array(
//                                    'wish_id' => $wish_id,
//                                    'token'   => $token,
//                                );
//                            }
//                        }
//                    }else{
//                        //调取生成订单接口
//                        $info = $wish->createOrder($wish_id);
//                        $arr['msg'] = $info['msg'];
//                        if($info['code'] == 1){
//                            $arr['code'] = 1;
//                            $arr['result'] = 'wish';
//                            $arr['data'] = array(
//                                'wish_id' => $wish_id,
//                                'token'   => $token,
//                            );
//                        }
//                    }
                    $msg = '心愿单已失效，不能继续砍价！';
                    if ($wishInfo['state'] != 3) {
                        $msg = '心愿单已取消，不可继续砍价！';
                        if ($wishInfo['state'] != 0) {
                            $msg = '心愿单已完成，不可继续砍价！';
                            if ($wishInfo['state'] != 2) {
                                $wishLogInfo = $wishLogModel->get(array("conditions"=>'wish_id = '.$wish_id .' AND inviter_id ='.$result['user_id']));
                                $msg = '您已经参加过这个活动咯！';
                                if(empty($wishLogInfo)){
                                    $res = $this->wish_log($wishInfo['user_id'],$result['user_id'],$wish_id,'register');
                                    $code = $res['code'];
                                    $msg = $res['msg'];
                                }
                            }
                        }
                    }
                }
            }
        }catch(\Exception $e){
            $arr['code'] = -1;
            $arr['msg'] = '网络错误';
        }
        $arr['code'] = $code;
        $arr['msg'] = $msg;
        echo json_encode($arr);
        exit();
    }

    function get_decrypt($data, $key = 'asa')
    {
        $key = md5($key);
        $x = 0;
        $data = base64_decode($data);
        $len = strlen($data);
        $l = strlen($key);
        for ($i = 0; $i < $len; $i++)
        {
            if ($x == $l)
            {
                $x = 0;
            }
            $char .= substr($key, $x, 1);
            $x++;
        }
        for ($i = 0; $i < $len; $i++)
        {
            if (ord(substr($data, $i, 1)) < ord(substr($char, $i, 1)))
            {
                $str .= chr((ord(substr($data, $i, 1)) + 256) - ord(substr($char, $i, 1)));
            }
            else
            {
                $str .= chr(ord(substr($data, $i, 1)) - ord(substr($char, $i, 1)));
            }
        }
        return $str;
    }

    //通过分享的心愿单帮好友砍价进行登录并砍价
    function loginWxBargain(){
        if(IS_POST){
            $wishModel = &m("wish");
            $memberModel = &m("member");
            $wishLogModel = &m('wish_log');

            $wish_id = $_POST['wish_id'];
            $phone = $_POST['phone'];
            $password = $_POST['password'];

            $memberModel->writelog('心愿单分享帮好友砍价：接收参数：'.json_encode($_POST));
            $code = -1;
            $msg = '网络信息错误';
            if($wish_id){
                $msg = '手机号有误';
                if (preg_match("/^1\d{10}$/", $phone)) {
                    $msg = '请填写密码';
                    if($password){
                        $memberInfo = $memberModel->get(array("conditions"=>"phone_mob = ".$phone));
                        $msg = '账号不存在！';
                        if(!empty($memberInfo)) {
                            $pas = md5($password);
                            $msg = '密码错误';
                            if ($memberInfo['password'] == $pas) {
                                $msg = '心愿单信息错误';
                                //查看心愿单内容
                                $wishInfo = $wishModel->get(array('conditions' => 'id = ' . $wish_id));
                                if (!empty($wishInfo)) {
                                    $msg = '心愿单已失效，不能继续砍价！';
                                    if ($wishInfo['state'] != 3) {
                                        $msg = '心愿单已取消，不可继续砍价！';
                                        if ($wishInfo['state'] != 0) {
                                            $msg = '心愿单已完成，不可继续砍价！';
                                            if ($wishInfo['state'] != 2) {
                                                $wishLogInfo = $wishLogModel->get(array("conditions"=>'wish_id = '.$wish_id.' AND inviter_id ='.$memberInfo['user_id']));
                                                $msg = '您已经参加过这个活动咯！';
                                                if(empty($wishLogInfo)){
                                                    $res = $this->wish_log($wishInfo['user_id'],$memberInfo['user_id'],$wish_id,'login');
                                                    $code = $res['code'];
                                                    $msg = $res['msg'];
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            $arr['code'] = $code;
            $arr['msg'] = $msg;
            echo json_encode($arr);
            exit();
        }else{
            $wish_id = $_GET['wish_id'];
            $invite_code = $_GET['invite_code'];
            if(!$wish_id || !$invite_code){
                $this->display('share.404.html');
                exit();
            }
            $this->assign('wish_id',$wish_id);
            $this->assign('invite_code',$invite_code);
            $this->display("share.404.html");
//            $this->display("share.loginWxBargain.html");
        }
    }


    //工具方法   完成砍价功能
    function get_wish_log_price($wish_id,$template_id){
        $wishLogModel = &m("wish_log");
        $wishPayModel = &m("wish_pay_log");
        $wishModel = &m("wish");
        $wishTemplateModel = &m("wish_template");
        //判断是否为老心愿单
        $res_old = $wishLogModel->get(array('conditions'=>'wish_id='.$wish_id.' AND stage = 0'));
        $res_old_money['smoney'] = $wishLogModel->getInvalid($wish_id);
        $res_wish = $wishModel->get(array("conditions"=>'id = '.$wish_id));
        $res_pay1 = $wishPayModel->get(array("conditions"=>"wish_id =".$wish_id.' AND type = 1'));

        if($res_old){
            if($res_old_money['smoney'] + $res_pay1['money'] >= $res_wish['goods_price']){
                return false;
            }
            return array(
                'money' => '30',
                'sign' => '',
                'stage' => '0',
                'fsh' => $res_old_money['smoney'] + 30 + $res_pay1['money']>= $res_wish['goods_price'] ? true : false
            );
        }


        if($res_old_money['smoney'] + $res_pay1['money'] >= $res_wish['goods_price']){
            return false;
        }

        $res_template = $wishTemplateModel->get(array("conditions"=>'template_id = '.$template_id));

        //商品原价
        $goods_price = $res_wish['goods_price']-$res_pay1['money'];

        //1  0.66 0.66

        //判断人数取最大的
        $assist_num2 = (int)($goods_price / $res_template['assist_money']);
        //确认帮砍人数
        $assist_num = (int)($res_template['assist_num']) > $assist_num2 ? (int)($res_template['assist_num']) : $assist_num2;
        //确认每人帮砍金额
        $assist_price = $res_template['assist_num'] > $assist_num2 ? round($goods_price/$res_template['assist_num'],2) : $res_template['assist_money'];
        //第一阶段人数
        $stage_num1 = (int)($assist_num * $res_template['firstphase_num_percentage']);
        //第二阶段人数
        $stage_num2 = (int)($assist_num * $res_template['secondphase_num_percentage']);
        //第三阶段人数
        $stage_num3 = (int)($assist_num * $res_template['thirdphase_num_percentage']);

        //取现在第几阶段了
        $res_log = $wishLogModel->getCounts($wish_id);
        if(!$res_log || $res_log < $stage_num1){
            //第一阶段
            //算人数
            //正人数
            $cond_people1 = array(
                'wish_id' => $wish_id,
                'sign' => '+',
                'stage' => 1
            );
            $res_plus1 = $wishLogModel->getTemplateCount($cond_people1);
            //负人数
            $cond_people2 = array(
                'wish_id' => $wish_id,
                'sign' => '-',
                'stage' => 1
            );
            $res_plus2 = $wishLogModel->getTemplateCount($cond_people2);
            if($res_plus1 >= $stage_num1/2){
                $sm1 = round($res_template['firstphase_money_percentage']*$goods_price/$stage_num1,2);
                $sm2 = (float)sprintf("%.2f",$this->randomFloat(0-$res_template['float_percentage'],0)*$sm1);
                $money = $sm1 + $sm2;
                $sign = $sm2 >= 0 ? '+' : '-';
                $stage = 1;
            }else if($res_plus2 >= $stage_num1/2){
                $sm1 = round($res_template['firstphase_money_percentage']*$goods_price/$stage_num1,2);
                $sm2 = (float)sprintf("%.2f",$this->randomFloat(0,(float)$res_template['float_percentage'])*$sm1);
                $money = $sm1 + $sm2;
                $sign = $sm2 >= 0 ? '+' : '-';
                $stage = 1;
            }else{
                $sm1 = round($res_template['firstphase_money_percentage']*$goods_price/$stage_num1,2);
                $sm2 = (float)sprintf("%.2f",$this->randomFloat(0-$res_template['float_percentage'],(float)$res_template['float_percentage'])*$sm1);
                $money = $sm1 + $sm2;
                $sign = $sm2 >= 0 ? '+' : '-';
                $stage = 1;
            }
        }else if($res_log >= $stage_num1 && $res_log < $stage_num1 + $stage_num2){
            //第二阶段

            //算人数
            //正人数
            $cond_people1 = array(
                'wish_id' => $wish_id,
                'sign' => '+',
                'stage' => 2
            );
            $res_plus1 = $wishLogModel->getTemplateCount($cond_people1);
            //负人数
            $cond_people2 = array(
                'wish_id' => $wish_id,
                'sign' => '-',
                'stage' => 2
            );
            $res_plus2 = $wishLogModel->getTemplateCount($cond_people2);
            if($res_plus1 > $stage_num2/2){
                $sm1 = round($res_template['secondphase_money_percentage']*$goods_price/$stage_num2,2);
                $sm2 = (float)sprintf("%.2f",$this->randomFloat(0-$res_template['float_percentage'],0)*$sm1);
                $money = $sm1 + $sm2;
                $sign = $sm2 >= 0 ? '+' : '-';
                $stage = 2;
            }else if($res_plus2 >= $stage_num2/2){
                $sm1 = round($res_template['secondphase_money_percentage']*$goods_price/$stage_num2,2);
                $sm2 = (float)sprintf("%.2f",$this->randomFloat(0,(float)$res_template['float_percentage'])*$sm1);
                $money = $sm1 + $sm2;
                $sign = $sm2 >= 0 ? '+' : '-';
                $stage = 2;
            }else{
                $sm1 = round($res_template['secondphase_money_percentage']*$goods_price/$stage_num2,2);
                $sm2 = (float)sprintf("%.2f",$this->randomFloat(0-$res_template['float_percentage'],(float)$res_template['float_percentage'])*$sm1);
                $money = $sm1 + $sm2;
                $sign = $sm2 >= 0 ? '+' : '-';
                $stage = 2;
            }
        }else if($res_log >= $stage_num1 + $stage_num2){
            //第三阶段
            //出去一二阶段剩余钱数
            $cond['wish_id'] = $wish_id;
            $cond['stage'] = array('IN','1,2');
            $res_t['surplus_money'] = $wishLogModel->getInvalid($wish_id,$cond);
            $surplus_money = $res_t['surplus_money'];


            //算人数
            //正人数
            $cond_people1 = array(
                'wish_id' => $wish_id,
                'sign' => '+',
                'stage' => 3
            );
            $res_plus1 = $wishLogModel->getTemplateCount($cond_people1);
            //负人数
            $cond_people2 = array(
                'wish_id' => $wish_id,
                'sign' => '-',
                'stage' => 3
            );
            $res_plus2 = $wishLogModel->getTemplateCount($cond_people2);
            if($res_plus1 >= $stage_num3/2){
                $sm1 = round(($goods_price-$surplus_money)/$stage_num3,2);
                $sm2 = (float)sprintf("%.2f",$this->randomFloat(0-$res_template['float_percentage'],0)*$sm1);
                $money = $sm1 + $sm2;
                $sign = $sm2 >= 0 ? '+' : '-';
                $stage = 3;
            }else if($res_plus2 >= $stage_num3/2){
                $sm1 = round(($goods_price-$surplus_money)/$stage_num3,2);
                $sm2 = (float)sprintf("%.2f",$this->randomFloat(0,(float)$res_template['float_percentage'])*$sm1);
                $money = $sm1 + $sm2;
                $sign = $sm2 >= 0 ? '+' : '-';
                $stage = 3;
            }else{
                $sm1 = round(($goods_price-$surplus_money)/$stage_num3,2);
                $sm2 = (float)sprintf("%.2f",$this->randomFloat(0-$res_template['float_percentage'],(float)$res_template['float_percentage'])*$sm1);
                $money = $sm1 + $sm2;
                $sign = $sm2 >= 0 ? '+' : '-';
                $stage = 3;
            }

            //算总钱数
            $rs_log['smoney'] = $wishLogModel->getInvalid($wish_id);
            //算总人数
            $res_log_count = $wishLogModel->getCounts($wish_id);
            if($rs_log['smoney'] + $money >= $goods_price){
                if($rs_log['smoney'] >= $goods_price){
                    return false;
                }
                if($res_log_count + 1 >= $assist_num - $res_template['plus_minus'] && $res_log_count + 1 <= $assist_num + $res_template['plus_minus']){
                    //正好在区间直接成交
                    $money = $goods_price - $rs_log['smoney'];
                    $fsh = true;
                }else if($res_log_count + 1 < $assist_num - $res_template['plus_minus']){
                    //不够人数 把钱下降
                    $money = round($money/($assist_num-$res_log_count),2);
                }else if($res_log_count + 1 > $assist_num - $res_template['plus_minus']){
                    //人数大于区间直接成交
                    $money = $goods_price-$rs_log['smoney'];
                    $fsh = true;
                }else{
                    //其他条件不动
                }
            }else{
                //其他条件不动
//            return false;
            }
        }
        return array(
            'money' => $money,
            'sign' => $sign,
            'stage' => $stage,
            'fsh' => $fsh ? $fsh = true : false
        );
    }
    //随机数
    function randomFloat($min = 0, $max = 1) {
        return $min + mt_rand() / mt_getrandmax() * ($max - $min);
    }

    function wish_log($user_id=3,$referid=222,$wish_id=2,$operation_type='login'){

        $rs = $this->get_wish_log_price($wish_id,2);

        $memberModel = &m('member');
        $memberModel->writelog('获取当前砍价的阶段信息返回：'.json_encode($rs));

        if($rs){
            $time = time();
            $data = array(
                'wish_id' => $wish_id,
                'user_id'=> $user_id,
                'inviter_id' => $referid,
                'money' => $rs['money'],
                'msg' => '帮砍金额',
                'create_time' => $time,
                'sign' => $rs['sign'],
                'stage' => $rs['stage']
            );
            $add = &m('wish_log')->add($data);
            $couponSettingModel = &m("coupon_setting");
            $memberCouponModel = &m('member_coupon');
            $res_coupon_setting = $couponSettingModel->get(array("conditions"=>"setting_id = 1"));

            //$rs['fsh'] 为true时  心愿单完成砍价活动  直接生成订单并发送到oms
            if($rs['fsh']){
                $wishModel = &m('wish');
                $result = $wishModel->createOrder($wish_id);
                if($result['code'] == -1){
                    $arr['code'] = -1;
                    $arr['msg'] = $result['msg'];
                    return $arr;
                }
            }
            $data_coupon = array(
                'coupon_name' => $res_coupon_setting['name'],
                'remark' => $res_coupon_setting['remark'],
                'money' => $res_coupon_setting['money'],
                'min_money' => $res_coupon_setting['min_money'],
                'user_id' => $referid,
                'start_time' => $time,
                'end_time' => $time + $res_coupon_setting['expiry_time'],
                'is_used' => 0,
            );
            $add_coupon = $memberCouponModel->add($data_coupon);
            if($add_coupon){
                //新注册用户赠送代金券
                if($operation_type == 'register'){
                    $register_coupon = $couponSettingModel->get(array("conditions"=>'setting_id = 4'));
                    $arr_coupon = array(
                        'coupon_name' => $register_coupon['name'],
                        'remark' => $register_coupon['remark'],
                        'money' => $register_coupon['money'],
                        'min_money' => $register_coupon['min_money'],
                        'user_id' => $referid,
                        'start_time' => $time,
                        'end_time' => $time+$register_coupon['expiry_time'],
                        'is_used' => 0,
                    );
                    $add_register_coupon = $memberCouponModel->add($arr_coupon);
                    if($add_register_coupon){
                        $code = 1;
                        $msg = '砍价成功';
                    }else{
                        $code = -1;
                        $msg = '砍价失败';
                    }
                }else{
                    $code = 1;
                    $msg = '砍价成功';
                }
            }else{
                $code = -1;
                $msg = '砍价失败';
            }
            $arr['code'] = $code;
            $arr['msg'] = $msg;
            return $arr;
        }else{
            $arr['code'] = -1;
            $arr['msg'] = '心愿单的价格与折扣不符！请联系客服！';
            return $arr;
        }
    }




    function testPhone(){
        $post = $_POST['phone'];
        $member = &m("member");
        $result = $member->check_mobile($post);
        print_r($result);die;

    }

    function shareGoods(){
        $res_goods = &m('goods')->get('goods_id='.$_GET['goods_id']);
        $sql = "SELECT * FROM ecm_goods_spec WHERE goods_id=".$_GET['goods_id']." GROUP BY spec_1value";
        $res_goods_spec =  &m('goodsspec')->getAll($sql);
        $data_spec1 = array();
        foreach ($res_goods_spec as $k => $v){
            $data_spec1[$k]['spec1s'] = $v['spec_1'];
        }
        $this->assign('goods',$res_goods);
        $this->assign('spec1s',$data_spec1);
        $this->display('goods.detail.html');
    }
}